var express = require('express');
var router = express.Router();
let jwt = require('jsonwebtoken')
var connection = require('../db/sql');

//新增收货地址
router.post('/api/addAddress', function (req, res, next) {
    //token
    let token = req.headers.token;
    let tokenObj = jwt.decode(token)

    //拿到前端给后端传入的数据
    let body = req.body
    let [name, tel, province, city, county, addressDetail, isDefault, areaCode] = [
        body.name,
        body.tel,
        body.province,
        body.city,
        body.county,
        body.addressDetail,
        body.isDefault,
        body.areaCode,
    ];



    //查询用户
    connection.query(`select * from user where tel= ${tokenObj.tel}`, function (error, results) {
        //用户id
        let uId = results[0].id;
        if (isDefault != 1) {
            //增加一条收货地址
            connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values (${uId},"${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function (err, result) {
                res.send({
                    data: {
                        code: 200,
                        success: true,
                        msg: '收货地址添加成功',
                    }


                })
            })
        } else {

            connection.query(`select * from address where uId = ${uId} and isDefault = ${isDefault}`, function (err, result) {
                if (result.length > 0) {
                    let addressId = result[0].id;
                    connection.query(`update address set isDefault = replace(isDefault,'1','0') where id= ${addressId}`, function () {

                        //增加一条收货地址
                        connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values (${uId},"${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function (e, r) {
                            res.send({
                                data: {
                                    code: 200,
                                    success: true,
                                    msg: '收货地址添加成功',
                                }


                            })
                        })

                    })
                } else {
                    //增加一条收货地址
                    connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values (${uId},"${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function (err, result) {
                        res.send({
                            data: {
                                code: 200,
                                success: true,
                                msg: '收货地址添加成功',
                            }


                        })
                    })
                }


            })
        }

    })

})

//查询收货地址
router.post('/api/selectAddress', function (req, res, next) {
    //token
    let token = req.headers.token;
    let tokenObj = jwt.decode(token)
    //查询用户
    connection.query(`select * from user where tel= ${tokenObj.tel}`, function (error, results) {
        //用户id
        let uId = results[0].id;

        connection.query(`select * from address where uId=${uId}`, function (err, result) {
            res.send({
                data: {
                    code: 200,
                    success: true,
                    msg: '查询成功',
                    data: result
                }
            })
        })
    })
})


//修改收货地址
router.post("/api/updateAddress", function (req, res, next) {
    //token
    let token = req.headers.token;
    let tokenObj = jwt.decode(token);
    //拿到前端给后端传入的数据
    let body = req.body;
    let [
        id,
        name,
        tel,
        province,
        city,
        county,
        addressDetail,
        isDefault,
        areaCode,
    ] = [
            body.id,
            body.name,
            body.tel,
            body.province,
            body.city,
            body.county,
            body.addressDetail,
            body.isDefault,
            body.areaCode,
        ];
    //查询用户
    connection.query(
        `select * from user where tel = ${tokenObj.tel}`,
        function (error, results) {
            //用户id
            let uId = results[0].id;
            //对应查询到0 或者 1 有没有默认收货地址
            connection.query(
                `select * from address where uId = ${uId} and isDefault = ${isDefault}`,
                function (err, result) {
                    if (result.length > 0) {
                        let addressId = result[0].id;
                        connection.query(
                            `update address set isDefault =0 where id = ${addressId}`,
                            function (e, r) {
                                let updateSql = `update address set uId = ? , name = ? , tel = ? , province = ? , city = ? ,county = ? , addressDetail = ? , isDefault = ? , areaCode = ? where id = ${id}`;
                                connection.query(
                                    updateSql,
                                    [
                                        uId,
                                        name,
                                        tel,
                                        province,
                                        city,
                                        county,
                                        addressDetail,
                                        isDefault,
                                        areaCode,
                                    ],
                                    function (errors, datas) {
                                        res.send({
                                            data: {
                                                code: 200,
                                                success: true,
                                                msg: "修改成功",
                                            },
                                        });
                                    }
                                );
                            }
                        );
                    } else {
                        let updateSql = `update address set uId = ? , name = ? , tel = ? , province = ? , city = ? ,county = ? , addressDetail = ? , isDefault = ? , areaCode = ? where id = ${id}`;
                        connection.query(
                            updateSql,
                            [
                                uId,
                                name,
                                tel,
                                province,
                                city,
                                county,
                                addressDetail,
                                isDefault,
                                areaCode,
                            ],
                            function (errors, datas) {
                                res.send({
                                    data: {
                                        code: 200,
                                        success: true,
                                        msg: "修改成功",
                                    },
                                });
                            }
                        );
                    }
                }
            );
        }
    );
});


//删除收货地址
router.post('/api/deleteAddress', function (req, res, next) {
    let id = req.body.id;
    connection.query(`delete from address where id= ${id}`, function (error, results) {
        res.send({
            data: {
                code: 200,
                success: true,
                msg: '删除成功'
            }
        })
    })
})


module.exports = router;
